<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-header">
        <h2 v-show="currentForm === 'resetStep1' || currentForm === 'resetStep2'"
          >重置统一登录密码</h2
        >
        <h2 v-show="currentForm === 'login' || currentForm === 'register'">One File</h2>
        <p v-show="currentForm === 'resetStep1' || currentForm === 'resetStep2'" class="subtitle"
          >请输入你注册的邮箱用于接收验证码，我们将为你重置密码。</p
        >
        <p v-show="currentForm === 'login'" class="subtitle">让你的文件收放自如！</p>
        <p v-show="currentForm === 'register'" class="subtitle"
          >只需一个 OneFile 账号，即可访问 OneFile 的所有服务。</p
        >
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="currentForm === 'login'"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
      >
        <el-form-item prop="email">
          <el-input
            v-model="loginForm.email"
            :prefix-icon="Message"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :prefix-icon="Lock"
            placeholder="请输入密码"
            show-password
            type="password"
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="login-button" type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>

        <el-form-item>
          <div class="action-links">
            <el-link :underline="false" type="primary" @click="switchToResetStep1"
              >忘记密码
            </el-link>
            <el-link :underline="false" type="primary" @click="switchToRegister">注册账号</el-link>
          </div>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else-if="currentForm === 'register'"
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
      >
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            :prefix-icon="Message"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            :prefix-icon="Lock"
            placeholder="请输入密码"
            show-password
            type="password"
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            :prefix-icon="Lock"
            placeholder="请确认密码"
            show-password
            type="password"
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="code">
          <div class="verification-code">
            <el-input v-model="registerForm.code" placeholder="请输入验证码"></el-input>
            <el-button
              :disabled="isCountingDown"
              style="height: 38px"
              @click="sendVerificationCode('register')"
            >
              {{ countDownText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button class="login-button" type="primary" @click="handleRegister">注册</el-button>
        </el-form-item>

        <el-form-item>
          <div class="action-links">
            <el-link :underline="false" type="primary" @click="switchToLogin">返回登录</el-link>
          </div>
        </el-form-item>
      </el-form>

      <!-- 重置密码步骤1：验证邮箱 -->
      <el-form
        v-else-if="currentForm === 'resetStep1'"
        ref="resetStep1FormRef"
        :model="resetForm"
        :rules="resetStep1Rules"
      >
        <el-form-item prop="email">
          <el-input
            v-model="resetForm.email"
            :prefix-icon="Message"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>

        <el-form-item prop="code">
          <div class="verification-code">
            <el-input v-model="resetForm.code" placeholder="请输入验证码"></el-input>
            <el-button
              :disabled="isCountingDown"
              style="height: 38px"
              @click="sendVerificationCode('reset')"
            >
              {{ countDownText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button class="login-button" type="primary" @click="verifyEmailAndProceed"
            >下一步
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="action-links">
            <el-link :underline="false" type="primary" @click="switchToLogin">返回登录</el-link>
          </div>
        </el-form-item>
      </el-form>

      <!-- 重置密码步骤2：输入新密码 -->
      <el-form
        v-else-if="currentForm === 'resetStep2'"
        ref="resetStep2FormRef"
        :model="resetForm"
        :rules="resetStep2Rules"
      >
        <el-form-item prop="password">
          <el-input
            v-model="resetForm.password"
            :prefix-icon="Lock"
            placeholder="请输入新密码"
            show-password
            type="password"
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="resetForm.confirmPassword"
            :prefix-icon="Lock"
            placeholder="请确认新密码"
            show-password
            type="password"
          >
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="login-button" type="primary" @click="handleResetPassword"
            >重置密码
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="action-links">
            <el-link :underline="false" type="primary" @click="switchToLogin">返回登录</el-link>
          </div>
        </el-form-item>
      </el-form>

      <div class="agreement">
        注册登录即表示同意<a style="color: #409eff">用户协议</a>和<a style="color: #409eff"
          >隐私政策</a
        >
      </div>
    </div>
    <!-- 页面底部备案信息 -->
    <div class="page-footer">
      <a class="beian-link" href="https://beian.miit.gov.cn/" target="_blank">
        桂ICP备2024049764号-1
      </a>
    </div>
  </div>
</template>

<script setup>
  import { Lock, Message } from '@element-plus/icons-vue'
  import { computed, reactive, ref } from 'vue'
  import { ElLoading, ElMessage } from 'element-plus'
  import {
    loginService,
    registerService,
    resetPasswordService,
    sendCodeService,
    verifyCodeService
  } from '@/api/user.js'
  import router from '@/router/index.js'
  import { useUserStore } from '@/stores/modules/user.js'
  import { useFileStore } from '@/stores/modules/file.js'

  const userStore = useUserStore()
  const fileStore = useFileStore()
  const currentForm = ref('login') // 'login', 'register', 'resetStep1', 'resetStep2'
  const countDown = ref(0)
  const isCountingDown = ref(false)
  const registerFormRef = ref(null)
  const loginFormRef = ref(null)
  const resetStep1FormRef = ref(null)
  const resetStep2FormRef = ref(null)

  const loginForm = reactive({
    email: 'i2oh0gzuy9@iwatermail.com',
    password: '123456'
  })

  const registerForm = reactive({
    email: '',
    password: '',
    confirmPassword: '',
    code: ''
  })

  const resetForm = reactive({
    email: '',
    code: '',
    password: '',
    confirmPassword: ''
  })

  const loginRules = {
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ]
  }

  const registerRules = {
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== registerForm.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    code: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 4, message: '验证码长度应为4位', trigger: 'blur' }
    ]
  }

  const resetStep1Rules = {
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    code: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 4, message: '验证码长度应为4位', trigger: 'blur' }
    ]
  }

  const resetStep2Rules = {
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== resetForm.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  const switchToLogin = () => {
    currentForm.value = 'login'
  }

  const switchToRegister = () => {
    if (import.meta.env.MODE !== 'development') {
      return ElMessage.warning('演示环境暂不支持注册')
    }
    currentForm.value = 'register'
  }

  const switchToResetStep1 = () => {
    if (import.meta.env.MODE !== 'development') {
      return ElMessage.warning('演示环境暂不支重置密码')
    }
    currentForm.value = 'resetStep1'
  }

  const switchToResetStep2 = () => {
    currentForm.value = 'resetStep2'
  }

  const handleLogin = () => {
    // 实现登录逻辑
    loginFormRef.value.validate(async isValid => {
      if (isValid) {
        const loading = ElLoading.service({
          lock: true,
          text: '登录中...',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        try {
          const res = await loginService({
            email: loginForm.email,
            password: loginForm.password
          })

          userStore.setToken(res.data.token)
          userStore.setId(res.data.id)
          userStore.setEmail(res.data.email)
          userStore.setRole(res.data.role)
          fileStore.setParentId(res.data.rootFileId)

          await router.push('/')
        } catch (err) {
          console.error(err)
        } finally {
          loading.close()
        }
      }
    })
  }

  const handleRegister = () => {
    // 实现注册逻辑
    registerFormRef.value.validate(async isValid => {
      if (isValid) {
        const loading = ElLoading.service({
          lock: true,
          text: '注册中...',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        try {
          await registerService({
            email: registerForm.email,
            password: registerForm.password,
            code: registerForm.code
          })
          ElMessage.success('注册成功')
          switchToLogin()
        } catch (err) {
          console.error(err)
        } finally {
          loading.close()
        }
      }
    })
  }

  // 验证邮箱和验证码，然后进入密码重置步骤
  const verifyEmailAndProceed = () => {
    resetStep1FormRef.value.validate(async isValid => {
      if (isValid) {
        const loading = ElLoading.service({
          lock: true,
          text: '验证中...',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        try {
          await verifyCodeService(resetForm.email, resetForm.code)
          // 验证成功后进入下一步
          switchToResetStep2()
        } catch (err) {
          console.error(err)
        } finally {
          loading.close()
        }
      }
    })
  }

  // 处理重置密码
  const handleResetPassword = () => {
    resetStep2FormRef.value.validate(async isValid => {
      if (isValid) {
        const loading = ElLoading.service({
          lock: true,
          text: '重置密码中...',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        try {
          await resetPasswordService(resetForm.email, resetForm.password, resetForm.code)
          ElMessage.success('密码重置成功，请登录')
          switchToLogin()
        } catch (err) {
          console.error(err)
        } finally {
          loading.close()
        }
      }
    })
  }

  const countDownText = computed(() => {
    return isCountingDown.value ? `${countDown.value}秒后重新发送` : '发送验证码'
  })

  const sendVerificationCode = type => {
    // 根据不同表单类型，校验邮箱
    let formRef
    let email

    if (type === 'register') {
      formRef = registerFormRef.value
      email = registerForm.email
    } else if (type === 'reset') {
      formRef = resetStep1FormRef.value
      email = resetForm.email
    }

    // 只校验邮箱字段
    formRef.validateField('email', async valid => {
      if (!valid) {
        // 邮箱验证失败
        return
      }

      // 邮箱验证通过，开始倒计时并发送验证码
      isCountingDown.value = true
      countDown.value = 120

      const timer = setInterval(() => {
        countDown.value--
        if (countDown.value <= 0) {
          clearInterval(timer)
          isCountingDown.value = false
        }
      }, 1000)

      // 调用发送验证码的API
      await sendCodeService(email)
      ElMessage.success('发送验证码成功')
    })
  }
</script>

<style scoped>
  .login-container {
    min-height: 100vh;
    height: 100vh;
    background: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .login-content {
    width: 320px;
    margin: 0 auto;
  }

  .login-header {
    text-align: center;
    margin-bottom: 30px;
  }

  .subtitle {
    color: #909399;
    margin-top: 8px;
  }

  .login-button {
    width: 100%;
    height: 38px;
  }

  .agreement {
    text-align: center;
    margin-top: 20px;
    color: #909399;
    font-size: 12px;
  }

  .action-links {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .verification-code {
    display: flex;
    gap: 10px;
  }

  .verification-code .el-input {
    flex: 1;
  }

  .verification-code .el-button {
    width: 120px;
  }

  ::v-deep .el-input__inner {
    height: 36px;
  }

  .login-container {
    min-height: 100vh;
    height: 100vh;
    background: #ffffff;
    display: flex;
    flex-direction: column; /* 改为纵向排列 */
    justify-content: center;
    align-items: center;
    position: relative; /* 为绝对定位做准备 */
  }

  .page-footer {
    position: absolute;
    bottom: 20px;
    width: 100%;
    text-align: center;
    color: #909399;
    font-size: 12px;
  }

  .beian-link {
    color: #909399;
    text-decoration: none;
  }

  .beian-link:hover {
    color: #409eff;
  }
</style>
